package com.weme.common.manager

import androidx.lifecycle.ProcessLifecycleOwner
import androidx.lifecycle.lifecycleScope
import com.osom.proto.message.NetworkOuterClass
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.launch

/**
 * 用来发送心跳包数据
 *
 * @author 
 */
object HeatBeat {

    private val lifecycleOwner = ProcessLifecycleOwner.get()
    private val applicationScope = lifecycleOwner.lifecycleScope

    private var heatBeatJob: Job? = null

    init {
        applicationScope.launch {
            /**
             * 监听一下心跳包的返回数据
             */
//            SocketManager.careReceiver(
//                CMD_PING_RESPONSE,
//                NetworkOuterClass.Network::parseFrom
//            ).observe(lifecycleOwner) {
//              //  debugOutput(false)
//            }
        }
    }



    fun sendHeatBeat() {
        if (heatBeatJob?.isActive == true) {
            return
        }
        heatBeatJob = applicationScope.launch {
            flow {
                while (true) {
                    delay(10 * 1000L)
                    emit(0)
                }
            }.collect {
                SocketManager.send(
                    NetworkOuterClass.Network.newBuilder().setCmdid(NetworkOuterClass.NetworkCommand.CMD_PING_REQUEST.number) // 心跳请求消息作为 payload
                        .build(),
                    NetworkOuterClass.NetworkCommand.CMD_PING_REQUEST.number,0
                )
            }
        }
    }

    fun stopHeatBeat() {
        if (heatBeatJob?.isActive == true) {
            heatBeatJob?.cancel()
        }
    }
}